package com.macro.mall.tiny.modules.pms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonPage;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.api.ResultCode;
import com.macro.mall.tiny.modules.pms.dto.GlobalSearchVO;
import com.macro.mall.tiny.modules.pms.model.PmsCoolTool;
import com.macro.mall.tiny.modules.pms.model.PmsElectricMasterData;
import com.macro.mall.tiny.modules.pms.model.PmsRepairData;
import com.macro.mall.tiny.modules.pms.service.PmsCoolToolService;
import com.macro.mall.tiny.modules.pms.service.PmsElectricMasterDataService;
import com.macro.mall.tiny.modules.pms.service.PmsRepairDataService;
import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.experimental.Delegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author Tyrone
 * @date 2025/3/7 01:52
 */
@RestController
@RequestMapping("/pms/pmsSearch")
@Api(tags = "PmsSearchController", description = "全局搜索")
@Tag(name = "PmsSearchController", description = "全局搜索")
public class PmsSearchController {

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private PmsRepairDataService pmsRepairDataService;

    @Autowired
    private PmsElectricMasterDataService pmsElectricMasterDataService;

    @Autowired
    private PmsCoolToolService pmsCoolToolService;

    @GetMapping("/getResentSearch")
    @ApiOperation("获取最近搜索")
    public CommonResult<List<String>> getResentSearch() {
        UmsMember member = MemberContext.getMember();
        if (member == null) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED);
        }
        return CommonResult.success(redisTemplate.opsForList().range(key + member.getId(), 0, -1));
    }

    @GetMapping("/deleteResentSearch")
    @ApiOperation("删除最近搜索")
    public CommonResult deleteResentSearch() {
        UmsMember member = MemberContext.getMember();
        if (member == null) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED);
        }
        redisTemplate.delete(key + member.getId());
        return CommonResult.success(null);
    }

    @GetMapping("/deleteResentSearchItem")
    @ApiOperation("删除最近搜索单个")
    public CommonResult deleteResentSearchItem(@RequestParam String keyword) {
        UmsMember member = MemberContext.getMember();
        if (member == null) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED);
        }
        redisTemplate.opsForList().remove(key + member.getId(), 0, keyword);
        return CommonResult.success(null);
    }

    private String key = "globalSearch:";

    @GetMapping("/global")
    @ApiOperation("全局搜索")
    public CommonResult<GlobalSearchVO> globalSearch(@RequestParam String keyword) {
        // Add the search term to the hot search list
        UmsMember member = MemberContext.getMember();
        if (member == null) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED);
        }
        // 删除重复记录
        redisTemplate.opsForList().remove(key + member.getId(), 0, keyword);
        // 添加到列表头部
        redisTemplate.opsForList().leftPush(key + member.getId(), keyword);
        // 限制列表长度
        redisTemplate.opsForList().trim(key + member.getId(), 0, 4);

        GlobalSearchVO globalSearchVO = new GlobalSearchVO();
        QueryWrapper<PmsCoolTool> pmsCoolToolQueryWrapper = new QueryWrapper<>();


        List<PmsCoolTool> coolTools = pmsCoolToolService.list(pmsCoolToolQueryWrapper.like("name", keyword)
                .apply("icon = url")
                .groupBy("name")
                .orderByDesc("id")
                .last("limit 5"));
        if (!coolTools.isEmpty()) {
            coolTools.forEach(coolTool -> {
                if (coolTool.getType() == 1){
                    coolTool.setIcon(null);
                }
                coolTool.setUrl(null);
            });
        }
        globalSearchVO.setCoolToolList(coolTools);

        QueryWrapper<PmsElectricMasterData> pmsElectricMasterDataQueryWrapper = new QueryWrapper<>();
        pmsElectricMasterDataQueryWrapper.ne("type", 0).ne("type", 1).like("name", keyword)
                .orderByDesc("id").last("limit 5");
        List<PmsElectricMasterData> electricMasterDataList = pmsElectricMasterDataService.list(pmsElectricMasterDataQueryWrapper);
        globalSearchVO.setElectricMasterDataList(electricMasterDataList);
        if (!electricMasterDataList.isEmpty()) {
            electricMasterDataList.forEach(electricMasterData -> {
                electricMasterData.setUrl(null);
            });
        }


        QueryWrapper<PmsRepairData> pmsRepairDataQueryWrapper = new QueryWrapper<PmsRepairData>();
        pmsRepairDataQueryWrapper.like("name", keyword).eq("type", 1).orderByDesc("id").last("limit 5");
        List<PmsRepairData> repairDataList = pmsRepairDataService.list(pmsRepairDataQueryWrapper);
        globalSearchVO.setRepairDataList(repairDataList);
        if (!repairDataList.isEmpty()) {
            repairDataList.forEach(repairData -> {
                repairData.setUrl(null);
            });
        }

        return CommonResult.success(globalSearchVO);
    }

    @GetMapping("/global/more")
    @ApiOperation("获取更多搜索结果")
    public CommonResult<CommonPage> globalSearch(@RequestParam Integer pageSize,
                                                 @RequestParam Integer pageNum,
                                                 @RequestParam Integer type,
                                                 @RequestParam String keyword) {
        // Add the search term to the hot search list
        keyword = URLDecoder.decode(keyword);
        if (type == 0) {
            Page<PmsCoolTool> coolToolPage = new Page<>(pageNum, pageSize, true);
            QueryWrapper<PmsCoolTool> pmsCoolToolQueryWrapper = new QueryWrapper<>();
            pmsCoolToolQueryWrapper.like("name", keyword)
                    .groupBy("name")
                    .orderByDesc("id");
            CommonPage<PmsCoolTool> pmsCoolToolCommonPage = CommonPage.restPage(pmsCoolToolService.page(coolToolPage, pmsCoolToolQueryWrapper));
            if (!pmsCoolToolCommonPage.getList().isEmpty()) {
                pmsCoolToolCommonPage.getList().forEach(pmsCoolTool -> {
                    if (pmsCoolTool.getType() == 1) {
                        pmsCoolTool.setIcon(null);
                    }
                    pmsCoolTool.setUrl(null);
                });
            }
            return CommonResult.success(pmsCoolToolCommonPage);
        }
        if (type == 1) {
            Page<PmsElectricMasterData> electricMasterDataPage = new Page<>(pageNum, pageSize, true);
            QueryWrapper<PmsElectricMasterData> pmsElectricMasterDataQueryWrapper = new QueryWrapper<>();
            pmsElectricMasterDataQueryWrapper.ne("type", 0).ne("type", 1).like("name", keyword)
                    .orderByDesc("id");
            CommonPage<PmsElectricMasterData> pmsElectricMasterDataCommonPage = CommonPage.restPage(pmsElectricMasterDataService.page(electricMasterDataPage, pmsElectricMasterDataQueryWrapper));
            if (!pmsElectricMasterDataCommonPage.getList().isEmpty()) {
                pmsElectricMasterDataCommonPage.getList().forEach(pmsElectricMasterData -> {
                    pmsElectricMasterData.setUrl(null);
                });
            }
            return CommonResult.success(pmsElectricMasterDataCommonPage);
        }

        if (type == 2) {
            Page<PmsRepairData> repairDataPage = new Page<>(pageNum, pageSize, true);
            QueryWrapper<PmsRepairData> pmsRepairDataQueryWrapper = new QueryWrapper<>();
            pmsRepairDataQueryWrapper.like("name", keyword).eq("type", 1).orderByDesc("id");
            CommonPage<PmsRepairData> pmsRepairDataCommonPage = CommonPage.restPage(pmsRepairDataService.page(repairDataPage, pmsRepairDataQueryWrapper));
            if (!pmsRepairDataCommonPage.getList().isEmpty()) {
                pmsRepairDataCommonPage.getList().forEach(pmsRepairData -> {
                    pmsRepairData.setUrl(null);
                });
            }
            return CommonResult.success(pmsRepairDataCommonPage);
        }

        return CommonResult.success(null);
    }

    public void addHotSearch(String searchTerm, double score) {
        redisTemplate.opsForZSet().add("hotSearch", searchTerm, score);
        // Keep only the top 100 hot searches to prevent the set from growing indefinitely
        redisTemplate.opsForZSet().removeRange("hotSearch", 0, -101);
    }

}
